# -*- coding:utf-8 -*-
# File: lab_cputemp.py
#向onenet平台已经创建的数据流发送数据点
import urllib.request
import json
import time
import datetime
from gpiozero import MCP3008

adc = MCP3008(channel=0)

APIKEY = 'xWOBphPlFSp9NJYKKWjhzzelgBo='  #改成你的APIKEY,需要在设备里创建


def convert_temp(gen):
    for value in gen:
        yield (value * 5 - 0.5) * 100


def get_temp():
    for temp in convert_temp(adc.values):
        return temp


def http_post():
    temperature = get_temp()  # get current temperature
    CurTime = datetime.datetime.now()  # get current time
    url = 'http://api.heclouds.com/devices/921282510/datapoints'
    values = {
        'datastreams': [{
            "id":
            "temp_room",
            "datapoints": [{
                "at": CurTime.isoformat(),
                "value": temperature
            }]
        }]
    }
    jdata = json.dumps(values)  # convert data to json format
    print("\n=== send data ===")
    print(jdata)
    data = bytes(jdata, 'utf-8')
    request = urllib.request.Request(url, data)
    request.add_header('api-key', APIKEY)
    request.get_method = lambda: 'POST'
    request = urllib.request.urlopen(request)
    return request.read()


if __name__ == "__main__":
    while True:
        time.sleep(5)
        resp = http_post()
        print("=== recv data ===")
        print(resp)
        time.sleep(5)
